package com.distribution.system.manager.channel.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.distribution.common.exception.ServiceException;
import com.distribution.common.utils.DateUtils;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.bo.*;
import com.distribution.system.domain.dto.ChoosePhoneDTO;
import com.distribution.system.domain.dto.SendCodeDTO;
import com.distribution.system.domain.entity.*;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.manager.channel.AbstractChannel;
import com.distribution.system.manager.channel.channelInfo.enums.WangHuiMingChannelEnum;
import com.distribution.system.service.AddressChannelService;
import com.distribution.system.utils.Base64Util;
import com.distribution.system.utils.MD5Util;
import com.distribution.system.utils.http.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author niejiandeng
 * @date 2023年07月10日 22:32
 */
@Slf4j
public class WangHuiMingChannel extends AbstractChannel {
    private static final Logger whmOrderSearchLog = LoggerFactory.getLogger("whmOrderSearchLog");

    public WangHuiMingChannel(CmccDaUpChannelInfoBO cmccDaUpChannelInfoBO) {
        super(cmccDaUpChannelInfoBO);
    }

    @Override
    public AddressInfoBo getChannelAddressInfo(AddressNameBo addressNameBo, AddressChannelService addressChannelService) {
        return null;
    }

    /**
     * 下单
     */
    @Override
    public String configPlaceOrderRequestParams(CmccDaOrder cmccDaOrder, CmccDaProduct cmccDaProduct, AddressInfoBo addressInfoBo) {
        log.info("配置王会明下单接口参数...");
        AddressChannel addressInfo = addressInfoBo.getAddressInfo();
        AddressChannel attributeInfo = addressInfoBo.getAttributeInfo();
        String method = interfaceUrlsMap.get(WangHuiMingChannelEnum.PLACE_ORDER_METHOD.getName());
        if ("1".equals(cmccDaProduct.getBroadbandFlag())) {
            method = interfaceUrlsMap.get(WangHuiMingChannelEnum.KD_PLACE_ORDER_METHOD.getName());
        }
        System.out.println("method = " + method);
        Map<String, Object> request = getRequest(method);
        JSONObject reqObj = new JSONObject();
        // 生成订单号
        orderId = "AY" + DateUtil.format(DateUtil.date(), "yyyyMMdd") + IdUtil.getSnowflake(1, 1).nextIdStr().substring(8,18);
        reqObj.put("outerId",orderId);
        reqObj.put("apiGoodsId",cmccDaOrder.getProductParam());
        reqObj.put("certName",cmccDaOrder.getCustomerName());
        reqObj.put("certNo",cmccDaOrder.getCustomerCertNo());
        if ("1".equals(cmccDaProduct.getSelectNumberFlag())) {
            reqObj.put("phoneNum",cmccDaOrder.getChoosePhone());
            if (!Objects.isNull(attributeInfo)) {
                reqObj.put("phoneCityCode",attributeInfo.getEssCityCode());
                reqObj.put("phoneProvinceCode",attributeInfo.getEssProvinceCode());
            }
            reqObj.put("uuid",cmccDaOrder.getPhoneUuid());
        }
        reqObj.put("receivePhone",cmccDaOrder.getCustomerPhone());
        if (!"1".equals(cmccDaProduct.getBroadbandFlag()) && "1".equals(cmccDaProduct.getCodeFlag())) {
            reqObj.put("smsCode",cmccDaOrder.getCode());
        }
        reqObj.put("postProvinceCode",addressInfo.getProvinceCode());
        reqObj.put("postCityCode", addressInfo.getCityCode());
        reqObj.put("postDistrictCode",addressInfo.getDistrictCode());
        reqObj.put("receiveAddr",addressInfo.getProvinceName() + addressInfo.getCityName() + addressInfo.getDistrictName() + cmccDaOrder.getAddressStreet());
        String base64 = Base64Util.encodeData(reqObj.toString());
        request.put("reqObj",base64);
        return new JSONObject(request).toString();
    }
    @Override
    public String sendPlaceOrderRequest(String requestJsonStr) {
        return HttpRequestUtils.sendPost(interfaceUrlsMap.get(WangHuiMingChannelEnum.BASE_URL.getName()), requestJsonStr);
    }
    @Override
    public ReqResult parsePlaceOrderResponseStr(JSONObject responseJsonObject) {
        if (!"100".equals(responseJsonObject.getString("code"))) {
            String msg = responseJsonObject.getString("msg") + responseJsonObject.getString("extMsg");
            if (responseJsonObject.getString("msg") != null && responseJsonObject.getString("msg").contains("limited by: calls are limited")) {
                msg = "当前该渠道下单过多,请稍后再试!" + msg;
            }
            return ReqResult.error(msg);
        } else {
            JSONObject response = responseJsonObject.getJSONObject("response");
            if (!"0000".equals(response.getString("rspCode"))) {
                return ReqResult.error(response.getString("rspDesc"));
            } else {
                UnOrderResultBo unOrderResultBo = new UnOrderResultBo();
                unOrderResultBo.setOrderId(orderId);
                unOrderResultBo.setChannelOrderNo(response.getString("orderNo"));
                return ReqResult.success(response.getString("rspDesc"), unOrderResultBo);
            }
        }
    }

    /**
     * 选号
     */
    @Override
    public String configChoosePhoneRequestParams(ChoosePhoneDTO choosePhoneDTO, CmccDaProduct cmccDaProduct, AddressInfoBo addressInfoBo) {
        log.info("请求王会明后台选择号码接口...");
        Map<String, Object> request = getRequest(interfaceUrlsMap.get(WangHuiMingChannelEnum.CHOOSE_PHONE_METHOD.getName()));
        JSONObject reqObj = new JSONObject();
        reqObj.put("apiGoodsId", cmccDaProduct.getProductParam());
        reqObj.put("provinceCode",addressInfoBo.getAttributeInfo().getEssProvinceCode());
        reqObj.put("cityCode",addressInfoBo.getAttributeInfo().getEssCityCode());
        reqObj.put("certName", choosePhoneDTO.getCertName());
        reqObj.put("receivePhone",choosePhoneDTO.getCustomerPhone());
        reqObj.put("receiveAddr", addressInfoBo.getAddressInfo().getProvinceName() + addressInfoBo.getAddressInfo().getCityName() + addressInfoBo.getAddressInfo().getDistrictName() + choosePhoneDTO.getAddressStreet());
        reqObj.put("certNo", choosePhoneDTO.getCertNum());
        reqObj.put("searchValue",StringUtils.isBlank(choosePhoneDTO.getKeywords()) ? "" : choosePhoneDTO.getKeywords());
        String base64 = Base64Util.encodeData(reqObj.toString());
        request.put("reqObj",base64);
        return new JSONObject(request).toString();
    }
    @Override
    public String sendChoosePhoneRequest(String requestJsonStr) {
        return HttpRequestUtils.sendPost(interfaceUrlsMap.get(WangHuiMingChannelEnum.BASE_URL.getName()), requestJsonStr);
    }
    @Override
    public ReqResult parseChoosePhoneResponseStr(JSONObject responseJsonObject) {
//        String a= "{\n" +
//                "    \"requestId\":\"18e2c999803a41e59d7a4c6b2df8eab6\",\n" +
//                "    \"code\":\"100\",\n" +
//                "    \"msg\":\"调用成功\",\n" +
//                "    \"message\":null,\n" +
//                "    \"extMsg\":null,\n" +
//                "    \"response\":{\n" +
//                "        \"rspCode\":\"0000\",\n" +
//                "        \"rspDesc\":\"下单成功\",\n" +
//                "        \"body\":{\n" +
//                "            \"numArray\":[\n" +
//                "                \"15624940133\",\n" +
//                "                \"15652376078\",\n" +
//                "                \"18515046892\",\n" +
//                "                \"15624942989\",\n" +
//                "                \"15652147140\",\n" +
//                "                \"13021959387\",\n" +
//                "                \"17611362911\",\n" +
//                "                \"13020081753\",\n" +
//                "                \"15510762541\",\n" +
//                "                \"15601075238\"\n" +
//                "            ]\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//        JSONObject jsonObject = JSONObject.parseObject(a);
        if (!"100".equals(responseJsonObject.getString("code"))) {
            String msg = responseJsonObject.getString("msg") + responseJsonObject.getString("extMsg");
            if (responseJsonObject.getString("msg") != null &&  responseJsonObject.getString("msg").contains("limited by: calls are limited")) {
                msg = "当前该渠道下单过多,请稍后再试!" + msg;
            }
            return ReqResult.error(msg);
        } else {
            JSONObject response = responseJsonObject.getJSONObject("response");
            if (!"0000".equals(response.getString("rspCode"))) {
                return ReqResult.error(response.getString("rspDesc"));
            } else {
                JSONArray numArray = response.getJSONObject("body").getJSONArray("numArray");
                List<String> phoneNumList = new ArrayList<>();
                for (Object object : numArray) {
                    String phoneNum = String.valueOf(object);
                    if (!StringUtils.isEmpty(phoneNum)){
                        phoneNumList.add(phoneNum);
                    }
                }
                ChoosePhoneResultBO choosePhoneResultBO = new ChoosePhoneResultBO();
                choosePhoneResultBO.setUuid(response.getString("uuid"));
                choosePhoneResultBO.setNumArray(phoneNumList);
                return ReqResult.success(choosePhoneResultBO);
            }
        }
    }

    @Override
    public ReqResult sendCardSmsCode(CmccDaProduct cmccDaProduct, SendCodeDTO sendCodeDTO) {
        Map<String, Object> request = getRequest(interfaceUrlsMap.get(WangHuiMingChannelEnum.SEND_SMS_METHOD.getName()));
        JSONObject reqObj = new JSONObject();
        reqObj.put("mobile",sendCodeDTO.getCustomerPhone());
        String base64 = Base64Util.encodeData(reqObj.toString());
        request.put("reqObj",base64);
//        String requestJson = super.buildJson(request);
//        JSONObject jsonObject = super.getJsonObject(channelUrlsMap.get(AoYaChannelEnum.BASE_URL.getName()), requestJson);
        String requestJson = new JSONObject(request).toString();
        JSONObject jsonObject = JSONObject.parseObject(HttpRequestUtils.sendPost(interfaceUrlsMap.get(WangHuiMingChannelEnum.BASE_URL.getName()), requestJson));
        if (!"100".equals(jsonObject.getString("code"))) {
            String msg = jsonObject.getString("msg") + jsonObject.getString("extMsg");
            if (jsonObject.getString("msg") != null && jsonObject.getString("msg").contains("limited by: calls are limited")) {
                msg = "当前该渠道下单过多,请稍后再试!" + msg;
            }
            return ReqResult.error(msg);
        } else {
            JSONObject jsonObject1 = jsonObject.getJSONObject("response");
            if (!"0000".equals(jsonObject1.getString("rspCode"))) {
                return ReqResult.error(jsonObject1.getString("rspDesc"));
            } else {
                return ReqResult.success(jsonObject1.getString("rspDesc"));
            }
        }
    }

    /**
     * 查看状态
     */
    @Override
    public RefreshOrderBO getRefreshOrderBO(CmccDaOrder cmccDaOrder) {
        // 王会明是根据订单编号更新的
        List<CmccDaOrder> orderList = new ArrayList<>();
        orderList.add(cmccDaOrder);
        Map<CmccDaOrder,RefreshOrderBO> refreshOrderBOMap = getRefreshOrderBOList(orderList);
        return refreshOrderBOMap.isEmpty() ? null : refreshOrderBOMap.get(cmccDaOrder);
    }
    // 王会明限制每次最多查100条
    @Override
    public Map<CmccDaOrder,RefreshOrderBO> getRefreshOrderBOMap(List<CmccDaOrder> orderList) {
        return getRefreshOrderBOList(orderList);
    }

    private Map<CmccDaOrder,RefreshOrderBO> getRefreshOrderBOList(List<CmccDaOrder> orderList) {
        // 提取订单号集合
        List<CmccDaOrder> subList = orderList.subList(0, Math.min(100, orderList.size()));
        String orderIds = subList.stream().map(CmccDaOrder::getOrderId).collect(Collectors.joining(","));
        // 请求
        Map<String, Object> request = getRequest(interfaceUrlsMap.get(WangHuiMingChannelEnum.SELECT_ORDER_METHOD.getName()));
        JSONObject reqObj = new JSONObject();
        reqObj.put("outerId", orderIds);
        String base64 = Base64Util.encodeData(reqObj.toString());
        request.put("reqObj",base64);
        String requestJson = new JSONObject(request).toString();
        whmOrderSearchLog.info("【王会明】查单请求 => {}",requestJson);
        JSONObject responseJson = JSONObject.parseObject(HttpRequestUtils.sendPost(interfaceUrlsMap.get(WangHuiMingChannelEnum.BASE_URL.getName()), requestJson));
        whmOrderSearchLog.info("【王会明】查单响应 => {}",responseJson.toString());
        Map<CmccDaOrder,RefreshOrderBO> refreshOrderBOMap = new HashMap<>();
        if (!"100".equals(responseJson.getString("code"))) {
            throw new ServiceException(responseJson.getString("msg"));
        }
        JSONArray jsonArray = responseJson.getJSONObject("response").getJSONArray("orderList");
        if (!jsonArray.isEmpty()){
            for (Object object : jsonArray) {
                RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
                JSONObject jsonObject = (JSONObject) object;
                refreshOrderBO.setOrderId(jsonObject.getString("outerId"));
                refreshOrderBO.setPhone(jsonObject.getString("preNumber"));
                String productStatus = "-1";
                String orderStatus = "2";
                String placeStatus = jsonObject.getString("status");
                if ("0".equals(placeStatus)){// 下单成功
                    String state = jsonObject.getString("state");
                    if ("6".equals(state)) {
                        productStatus = "1";
                        orderStatus = "3";
                    }else if ("1".equals(state)) {// 激活
                        productStatus = "1";
                        orderStatus = "3";
                    }
                }else {// 下单失败
                    orderStatus = "-1";
                }
                refreshOrderBO.setProductStatus(productStatus);
                refreshOrderBO.setStatus(orderStatus);
                refreshOrderBO.setScMoney((String) jsonObject.get("rechargeAmount"));
                refreshOrderBO.setStatusMsg((String) jsonObject.get("placeFailure"));
                CmccDaOrder cmccDaOrder = orderList.stream().filter(f -> StringUtils.equals(f.getOrderId(), refreshOrderBO.getOrderId())).collect(Collectors.toList()).get(0);
                refreshOrderBOMap.put(cmccDaOrder, refreshOrderBO);
            }
        }
        return refreshOrderBOMap;
    }


    public Map<String,Object> getRequest(String method) {
        StringBuilder stringBuffer = new StringBuilder();
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        String tripartiteApiAppId = interfaceParamsMap.get(WangHuiMingChannelEnum.APP_ID.getName());
        String tripartiteApiAppKey = interfaceParamsMap.get(WangHuiMingChannelEnum.APP_SECRET.getName());
        String timestamp = DateUtils.dateTimeHHmm();
        StringBuilder append = stringBuffer.append(tripartiteApiAppId).append(tripartiteApiAppKey).append(timestamp)
                .append(tripartiteApiAppId).append(tripartiteApiAppKey).append(method);
        String sign =  MD5Util.stringToMD5(MD5Util.stringToMD5(append.toString()));
        stringObjectHashMap.put("appId",tripartiteApiAppId);
        stringObjectHashMap.put("timestamp",timestamp);
        stringObjectHashMap.put("method",method);
        stringObjectHashMap.put("sign",sign);
        return stringObjectHashMap;
    }

    @Override
    public void refreshChannelCommission(CmccDaUpChannelInfo cmccDaUpChannelInfo) {
    }
}
